package product;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SaleInput extends JFrame {

	HashMap<String, StockData> sto;
	Vector<String> vec;
	DefaultTableModel model;
	int saleCnt;
	int index = -1;// 마우스클릭된 정보가 ArrayList어디에 위치해있는지를 찾아서 저장
	DecimalFormat df = new DecimalFormat("###,###,###.##");
	ArrayList<SaleData> aSal;
	HashMap<String, SaleTotal> hSal;
	int stock;

	private JPanel contentPane;
	private JLabel lblNewLabel;
	private JLabel lblNewLabel_1;
	private JLabel lblNewLabel_2;
	private JLabel lblNewLabel_3;
	private JLabel lblNewLabel_5;
	private JTextField proCode;
	private JTextField proName;
	private JTextField proPrice;
	private JTextField saleEa;
	private JTextField saleTot;
	private JButton btnSale;

	/**
	 * Create the frame.
	 */
	public SaleInput(HashMap<String, StockData> s, Vector<String> v,
			DefaultTableModel m, ArrayList<SaleData> a,
			HashMap<String, SaleTotal> h, int cnt, int i) {
		this.sto = s;
		this.vec = v;
		this.model = m;
		this.aSal = a;
		this.hSal = h;
		this.saleCnt = cnt;
		this.index = i;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 222, 209);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getLabel_2());
		contentPane.add(getLabel_3());
		contentPane.add(getLblNewLabel_2());
		contentPane.add(getLblNewLabel_3());
		contentPane.add(getLblNewLabel_5());
		contentPane.add(getProCode());
		contentPane.add(getProName());
		contentPane.add(getProPrice());
		contentPane.add(getSaleEa());
		contentPane.add(getSaleTot());
		contentPane.add(getBtnSale());

		proCode.setText(vec.get(0));
		proName.setText(vec.get(1));
		String str = df.format(Double.parseDouble(vec.get(2)));
		proPrice.setText(str + "원");
		stock = Integer.parseInt(vec.get(3));

	}

	public String replace(String s) {
		String temp = s.replace(",", "");
		String temp2 = temp.replace("원", "");
		return temp2;
	}

	public void compute() {
		try {
			int ea = Integer.parseInt(saleEa.getText());
			if (ea > stock) {
				JOptionPane.showMessageDialog(null, "재고수량이 모자랍니다.");
				saleEa.setText("");
				saleTot.setText("");
				btnSale.setEnabled(false);
				return;
			}
			int price = Integer.parseInt(replace(proPrice.getText()));
			int tot = ea * price;
			String str = df.format((double) tot);
			saleTot.setText(str + "원");
			btnSale.setEnabled(true);
		} catch (Exception e) {

		}
	}

	public void productSale() {
		try {
			String code = proCode.getText();
			String name = proName.getText();
			int price = Integer.parseInt(replace(proPrice.getText()));// (,)와(원)을
																		// 제거
			int ea = Integer.parseInt(saleEa.getText());
			int eao = ea;
			int tot = Integer.parseInt(replace(saleTot.getText()));// (,)와(원)을
																	// 제거

			SaleData data = new SaleData(code, name, price, ea, tot, saleCnt);
			saleCnt++;
			Sale.setSaleCnt(saleCnt);
			aSal.add(data);

			if (hSal.get(code) == null) {
				SaleTotal data2 = new SaleTotal(code, name, price, ea, tot);
				hSal.put(code, data2);
			} else {

				int ori = hSal.get(code).getSaleEa();
				ea = ea + ori;
				tot = ea * price;
				SaleTotal data2 = new SaleTotal(code, name, price, ea, tot);
				hSal.put(code, data2);

			}
			stock = stock - eao;
			StockData data3 = new StockData(code, name, price, (stock));
			sto.put(code, data3);// 재고수량 변경
			model.setValueAt(String.valueOf((stock)), index, 3);

			try {
				FileOutputStream fw = new FileOutputStream("SaleList.dat");
				ObjectOutputStream bw = new ObjectOutputStream(fw);
				bw.writeObject(aSal);// 파일저장
				bw.close();
				fw.close();
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("SaleList.dat 저장 실패");
			}

			try {
				FileOutputStream fw = new FileOutputStream("SaleTotal.dat");
				ObjectOutputStream bw = new ObjectOutputStream(fw);
				bw.writeObject(hSal);// 파일저장
				bw.close();
				fw.close();
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("SaleTotal.dat 저장 실패");
			}

			try {
				FileOutputStream fw = new FileOutputStream("StockList.dat");
				ObjectOutputStream bw = new ObjectOutputStream(fw);
				bw.writeObject(sto);// 파일저장
				bw.close();
				fw.close();
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("StockList.dat 저장 실패");
			}

			try {
				ObjectOutputStream dos = new ObjectOutputStream(
						new FileOutputStream("saleCnt.ser"));
				dos.writeObject(new Integer(saleCnt));
				// saleCnt변수를 파일로 저장시켜 프로그램을 껏다가 켯을때도 생산번호가 이어져 나갈수 있게함
				dos.close();
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("saleCnt.ser저장 실패");
			}

			System.out.println("저장성공");

		} catch (NumberFormatException en) {
			JOptionPane.showMessageDialog(null, "형식에 맞지않는 입력형식입니다.");
		}

		catch (Exception e) {
			System.out.println("error");
		}
	}

	private JLabel getLabel_2() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("제품 코드");
			lblNewLabel.setBounds(12, 10, 57, 15);
		}
		return lblNewLabel;
	}

	private JLabel getLabel_3() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("제품 명");
			lblNewLabel_1.setBounds(12, 35, 57, 15);
		}
		return lblNewLabel_1;
	}

	private JLabel getLblNewLabel_2() {
		if (lblNewLabel_2 == null) {
			lblNewLabel_2 = new JLabel("단가");
			lblNewLabel_2.setBounds(12, 60, 57, 15);
		}
		return lblNewLabel_2;
	}

	private JLabel getLblNewLabel_3() {
		if (lblNewLabel_3 == null) {
			lblNewLabel_3 = new JLabel("수량");
			lblNewLabel_3.setBounds(12, 88, 57, 15);
		}
		return lblNewLabel_3;
	}

	private JLabel getLblNewLabel_5() {
		if (lblNewLabel_5 == null) {
			lblNewLabel_5 = new JLabel("총액");
			lblNewLabel_5.setBounds(12, 113, 57, 15);
		}
		return lblNewLabel_5;
	}

	private JTextField getProCode() {
		if (proCode == null) {
			proCode = new JTextField();
			proCode.setEditable(false);
			proCode.setBounds(81, 7, 116, 21);
			proCode.setColumns(10);
		}
		return proCode;
	}

	private JTextField getProName() {
		if (proName == null) {
			proName = new JTextField();
			proName.setEditable(false);
			proName.setColumns(10);
			proName.setBounds(81, 32, 116, 21);
		}
		return proName;
	}

	private JTextField getProPrice() {
		if (proPrice == null) {
			proPrice = new JTextField();
			proPrice.setEditable(false);
			proPrice.setColumns(10);
			proPrice.setBounds(81, 57, 116, 21);
		}
		return proPrice;
	}

	private JTextField getSaleEa() {
		if (saleEa == null) {
			saleEa = new JTextField();
			saleEa.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent arg0) {
					compute();
				}
			});
			saleEa.setColumns(10);
			saleEa.setBounds(81, 85, 116, 21);
		}
		return saleEa;
	}

	private JTextField getSaleTot() {
		if (saleTot == null) {
			saleTot = new JTextField();
			saleTot.setEditable(false);
			saleTot.setColumns(10);
			saleTot.setBounds(81, 110, 116, 21);
		}
		return saleTot;
	}

	private JButton getBtnSale() {
		if (btnSale == null) {
			btnSale = new JButton("판매");
			btnSale.setEnabled(false);
			btnSale.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					productSale();
					btnSale.setEnabled(false);
					saleEa.setText("");
					saleTot.setText("");
				}
			});
			btnSale.setBounds(81, 141, 116, 23);
		}
		return btnSale;
	}
}
